package com.lemon.jvm.hotspot.src.share.vm.classfile;


import com.lemon.jvm.hotspot.src.share.vm.oops.InstanceKlass;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

public class BootClassLoader {

    public static final String SUFFIX = ".class";

    private final String classPath;

    /**
     * 用于存储该类加载器加载的所有类
     */
    private static Map<String, InstanceKlass> classLoaderData = new HashMap<>();

    public BootClassLoader(String classPath) {
        this.classPath = classPath;
    }

    public InstanceKlass loadKlass(final String name) {
        try {
            return loadKlass(name, true);
        } catch (IOException e) {
            throw new RuntimeException("Class Not Found!", e);
        }
    }

    public InstanceKlass loadKlass(final String name, boolean resolve) throws IOException {
        InstanceKlass instanceKlass = findLoadedClass(name);
        if (instanceKlass != null) {
            return instanceKlass;
        }

        instanceKlass = readAndParse(name);

        if (resolve) {

        }
        return instanceKlass;
    }

    private InstanceKlass readAndParse(String name) throws IOException {
        String tmpName = name.replace('.', '/');
        String filePath = classPath + tmpName + SUFFIX;

        // 读取字节码文件
        byte[] content = Files.readAllBytes(new File(filePath).toPath());

        // 解析字节码文件
        InstanceKlass klass = ClassFileParser.parseClassFile(content);

        // 存入
        classLoaderData.put(name, klass);

        return klass;
    }

    private InstanceKlass findLoadedClass(String name) {
        return classLoaderData.get(name);
    }

}
